package chapter08

/**
 * 偏函数
 *
 * @author cdhuangchao3
 * @date 2023/6/11 5:17 PM
 */
object Test06_PartialFunc {
  def main(args: Array[String]): Unit = {

    val list = List(("a", 12), ("b", 35), ("c", 27), ("a", 5))

    // 1.map转换，实现 key不变，value 2倍
    val newList: List[(String, Int)] = list.map(tuple => (tuple._1, tuple._2 * 2))

    // 2.用模式匹配对元组元素赋值
    list.map(
      tuple => {
        tuple match {
          case (word, count) => (word, count * 2)
        }
      }
    )

    // 3.省略lambda表达式写法，简化
    val newList3: List[(String, Int)] = list.map {
      case (word, count) => (word, count * 2)
    }
    println(newList3)

    // 偏函数的应用，求绝对值
    // 对输入数据分为不同的情形： 正、负、0
    val positiveAbs: PartialFunction[Int, Int] = {
      case x if x > 0 => x
    }
    val negativeAbs: PartialFunction[Int, Int] = {
      case x if x < 0 => -x
    }
    val zeroAbs: PartialFunction[Int, Int] = {
      case 0 => 0
    }

    def abs(x:Int):Int = (positiveAbs orElse negativeAbs orElse zeroAbs)(x)

    println(abs(-67))
    println(abs(36))
    println(abs(0))
  }
}
